<template>
  <div class="systemUserList">
    <div class="filter-container">
      <el-input
        v-model="listQuery.search.username"
        placeholder="用户名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.search.name"
        placeholder="姓名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.search.mobile"
        placeholder="手机号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <el-input
        v-model="listQuery.search.email"
        placeholder="邮箱"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.search.status"
        placeholder="状态"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in statusOptions"
          :key="item.key"
          :label="item.value"
          :value="item.key"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        查询
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>
    <el-scrollbar>
      <el-table
        v-loading="listLoading"
        :data="list"
        stripe
        fit
        highlight-current-row
        style="width: 100%;margin-bottom: 20px;"
      >
        <el-table-column
          label="姓名"
          :min-width="settings['tableWidth']['name']"
          align="left"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.name || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户名" width="120px" align="left">
          <template slot-scope="scope">
            <span>{{ scope.row.username || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="ID" width="80" align="right">
          <template slot-scope="scope">
            <span>{{ scope.row.id || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="手机号" width="120px" align="left">
          <template slot-scope="scope">
            <span>{{ scope.row.mobile || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" width="180px" align="left">
          <template slot-scope="scope">
            <span>{{ scope.row.email || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="120px" align="left">
          <template slot-scope="scope">
            <span>{{ scope.row.remark || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="状态" min-width="80">
          <template slot-scope="{ row }">
            <el-tag
              :disable-transitions="true"
              :type="row.status | userStatusBgFilter"
              :key="row.id"
            >
              {{ row.status | userStatusFilter }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="220">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="handleUpdate(row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-paperclip"
              @click="handleDetail(row.id, row.name)"
            >
              授权
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>

    <!-- <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="listQuery.page.current"
      :page-sizes="[10, 20, 50]"
      :page-size="listQuery.page.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination> -->
    <!-- 弹窗配置 -->
    <el-dialog
      :modal-append-to-body="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="600px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model.sync="tempData"
        label-position="right"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="tempData.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="tempData.name" placeholder="名字" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="tempData.mobile" placeholder="手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="tempData.email" placeholder="邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="tempData.password" placeholder="密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="retype_password">
          <el-input v-model="tempData.retype_password" placeholder="确认密码" />
        </el-form-item>
        <el-form-item
          label="状态"
          prop="status"
          v-if="dialogStatus === 'update'"
        >
          <template v-if="Number(tempData.originalStatus) === 0">
            <el-switch
              key="wait"
              style="display: block"
              v-model="tempData.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#67C23A"
              inactive-color="#909399"
              active-text="激活"
              inactive-text="待激活"
            >
            </el-switch>
          </template>
          <template v-else>
            <el-switch
              key="use"
              style="display: block"
              v-model="tempData.status"
              :active-value="1"
              :inactive-value="2"
              active-color="#67C23A"
              inactive-color="#F56C6C"
              active-text="激活"
              inactive-text="停用"
            >
            </el-switch>
          </template>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2 }"
            maxlength="100"
            minRows="2"
            show-word-limit
            v-model="tempData.remark"
            placeholder="请填写备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ '取消' }}
        </el-button>
        <el-button
          type="primary"
          :loading="confirmButtonLoading"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
// 具体用法查看官方API:https://github.com/kaorun343/vue-property-decorator
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import {
  systemGetUserList,
  systemCreateUser,
  systemModifyUser
} from '@/api/system/system'
import { parseTimeJS as parseTime } from '@/utils'
import { Form } from 'element-ui'
import { cloneDeep } from 'lodash'
import { isValidMobile, isValidEmail } from '@/utils/validate'
import { UserModule } from '@/store/modules/user'

interface IUserData {
  username: string
  name: string
  mobile: string
  email: string
  password: string
  retype_password: string
  remark: string
}
const defaultData: IUserData = {
  username: '',
  name: '',
  mobile: '',
  email: '',
  password: '',
  retype_password: '',
  remark: ''
}
@Component({
  name: 'systemUserList',
  components: {
    //引用的组件在这里声明
  }
})
export default class extends Vue {
  private tempData = defaultData
  private validateName = (rule: any, value: string, callback: Function) => {
    if (value.length < 1) {
      callback(new Error('请输入用户名'))
    } else {
      callback()
    }
  }
  private validateMobile(rule: any, value: string, callback: Function) {
    if (this.loginMethods.mobile) {
      if (!isValidMobile(value)) {
        return callback(new Error('请输入正确的手机号码'))
      }
      callback()
    } else {
      if (value && !isValidMobile(value)) {
        return callback(new Error('请输入正确的手机号码'))
      }
      callback()
    }
  }
  private validatePassword = (rule: any, value: string, callback: Function) => {
    if (typeof value === 'string' && value.length < 6) {
      callback(new Error('密码不能低于6位'))
    } else {
      callback()
    }
  }
  private validateRetypePassword = (
    rule: any,
    value: string,
    callback: Function
  ) => {
    if (typeof value === 'string' && value.length < 6) {
      callback(new Error('密码不能低于6位'))
    } else if (
      value !== ((this.$refs['dataForm'] as Form).model as IUserData).password
    ) {
      callback(new Error('密码输入不一致'))
    } else {
      callback()
    }
  }
  @Prop({ default: '' }) private propExp1!: string
  // @Prop({ required: true }) private propExp2?: boolean
  private dataExp: any = ''
  private statusOptions = [
    {
      value: '待激活',
      key: 0
    },
    {
      value: '激活',
      key: 1
    },
    {
      value: '停用',
      key: 2
    }
  ]
  // 弹窗配置
  private dialogStatus = ''
  private dialogFormVisible = false
  private textMap = {
    update: '编辑',
    create: '新增'
  }
  get rules() {
    return {
      username: [
        {
          required: !!this.loginMethods.username,
          message: '请填写用户名',
          trigger: 'blur'
        }
      ],
      name: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
      mobile: [
        {
          required: !!this.loginMethods.mobile,
          validator: this.validateMobile,
          trigger: 'blur'
        }
      ],
      email: [
        {
          required: !!this.loginMethods.email,
          type: 'email',
          message: '请输入正确的邮箱',
          trigger: 'blur'
        }
      ],
      password: [
        {
          required: this.dialogStatus === 'create',
          validator: this.validatePassword,
          trigger: 'blur'
        }
      ],
      retype_password: [
        {
          required: this.dialogStatus === 'create',
          validator: this.validateRetypePassword,
          trigger: 'blur'
        }
      ]
    }
  }

  get loginMethods() {
    const md: any = UserModule.sysConfig
      ? UserModule.sysConfig.loginMethods
      : {}
    return md
  }

  mounted() {
    this.getList()
  }
  private confirmButtonLoading = false

  // 表loading状态
  private listLoading: boolean = false
  private list = []
  private total = 0
  // 公共查询对象
  private listQuery = {
    search: {
      username: '',
      name: '',
      mobile: '',
      email: '',
      status: undefined
    },
    orderby: {
      field: undefined,
      direction: undefined
    }
  }
  // 跳转页码查询
  handleCurrentChange(val: any) {
    this.getList()
  }
  // size切换查询
  private handleSizeChange(val: any) {
    this.getList()
  }
  private async getList() {
    this.listLoading = true
    // ajax 请求相应list
    try {
      const { data } = await systemGetUserList(this.listQuery)
      this.list = data.list.map((v: any) => {
        this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
        v.originalStatus = v.status // will be used when user click the cancel botton
        return v
      })
    } catch (error) {
      console.error(error)
    } finally {
      this.listLoading = false
    }
  }
  private handleFilter() {
    this.getList()
  }
  //下载
  private handleDownload() {}
  // 新增
  private handleCreate() {
    this.resetData()
    this.dialogStatus = 'create'
    this.dialogFormVisible = true
    this.$nextTick(() => {
      ;(this.$refs['dataForm'] as Form).clearValidate()
    })
  }
  private resetData() {
    this.tempData = cloneDeep(defaultData)
  }
  // 新增
  private createData() {
    ;(this.$refs['dataForm'] as Form).validate(async valid => {
      if (valid) {
        this.confirmButtonLoading = true
        try {
          const { data } = await systemCreateUser(this.tempData)
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        } catch (error) {
          console.log(error)
        } finally {
          this.dialogFormVisible = false

          this.confirmButtonLoading = false
        }
      }
    })
  }
  // 更新
  private updateData() {
    ;(this.$refs['dataForm'] as Form).validate(async valid => {
      if (valid) {
        this.confirmButtonLoading = true
        try {
          const { data } = await systemModifyUser(this.tempData)
          this.dialogFormVisible = false
          this.confirmButtonLoading = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        } catch (error) {
          console.log(error)
        } finally {
          this.dialogFormVisible = false

          this.confirmButtonLoading = false
        }
      }
    })
  }

  // 打开弹窗编辑
  private async handleUpdate(row: any) {
    this.tempData = cloneDeep(row)
    this.dialogStatus = 'update'
    this.dialogFormVisible = true
    this.$nextTick(() => {
      ;(this.$refs['dataForm'] as Form).clearValidate()
    })
  }
  // 查看角色详情同事授权角色
  private handleDetail(id: string, name: string) {
    this.$router.push({
      path: '/system/user/detail?user_id=' + id + '&name=' + name
    })
  }
}
</script>

<style lang="scss" scoped>
.systemUserList {
  padding: 20px;
}
</style>
